package advertising

import (
	"encoding/json"
	"fmt"
	"gitee.com/alex_li/amazon-rpt/internal/rest"
	"github.com/lishimeng/go-log"
)

type AmazonPagerV3 struct {
	StartIndex int `json:"startIndex,omitempty"`
	Count      int `json:"count,omitempty"`
}

type SbKeywordListV3Req struct {
	AmazonPagerV3
	MatchTypeFilter  string `json:"matchTypeFilter,omitempty"`
	StateFilter      string `json:"stateFilter,omitempty"` // "enabled" "paused" "archived"
	CampaignIdFilter string `json:"campaignIdFilter,omitempty"`
	AdGroupIdFilter  string `json:"adGroupIdFilter,omitempty"`
	KeywordIdFilter  string `json:"keywordIdFilter,omitempty"`
}

type KeywordUpdateItemV3 struct {
	KeywordId  int64   `json:"keywordId,omitempty"`
	AdGroupId  int64   `json:"adGroupId,omitempty"`
	CampaignId int64   `json:"campaignId,omitempty"`
	State      string  `json:"state,omitempty"`
	Bid        float64 `json:"bid,omitempty"`
}
type KeywordUpdateV3Req struct {
	Keywords []KeywordUpdateItemV3 `json:"keywords,omitempty"`
}

type SbKeywordListV3Resp struct {
}

func (c *Client) UpdateSbKeyword(req KeywordUpdateV3Req) (resp map[string]any) {

	const action = "/sb/keywords"
	resp = make(map[string]any)
	r, err := c.request()
	if err != nil {
		return
	}
	bs, _ := json.Marshal(req)
	log.Info(string(bs))
	err = r.Path(action).Body(req.Keywords).Response(&resp).
		Expect(207).
		Accept("application/vnd.sbkeywordresponse.v3+json").
		Json("PUT", "application/json")
	if err != nil {
		log.Info(err)
		return
	}
	return
}

func (c *Client) ListSbKeyword(req SbKeywordListV3Req) (resp KeywordListResp, err error) {
	const action = "/sb/keywords"

	bs, err := json.Marshal(req)
	if err != nil {
		log.Info(err)
		return
	}
	log.Info(string(bs))
	var mapReq = make(map[string]any)
	err = json.Unmarshal(bs, &mapReq)
	if err != nil {
		log.Info(err)
		return
	}

	r, err := c.request()
	if err != nil {
		return
	}
	for k, v := range mapReq {
		r = r.Query(k, fmt.Sprintf("%v", v))
	}
	var respItem []KeywordInfoV3
	err = r.Path(action).Response(&respItem).
		Accept("application/vnd.sbkeyword.v3.2+json").
		Json(rest.GET)
	if err != nil {
		log.Info(err)
		return
	}
	for _, item := range respItem {
		var kw KeywordInfo
		kw.CampaignId = fmt.Sprintf("%v", item.CampaignId)
		kw.AdGroupId = fmt.Sprintf("%v", item.AdGroupId)
		kw.KeywordId = fmt.Sprintf("%v", item.KeywordId)
		kw.KeywordText = item.KeywordText
		kw.State = item.State
		kw.MatchType = item.MatchType
		kw.Bid = item.Bid
		resp.Keywords = append(resp.Keywords, kw)
	}
	resp.TotalResults = len(respItem)
	return
}
